﻿// owner 蒋家伟

#include "Log.h"

// std
#include <stdio.h>

// qt
#include <QFile>
#include <QTextStream>
#include <QDir>
#include <QDateTime>

using namespace jsdk;

Log::Log(void)
{
    // 日志等级字符串标示
    m_sLogLevel[eLogLevelNormal] = u8"普通";
    m_sLogLevel[eLogLevelWarning] = u8"警告";
    m_sLogLevel[eLogLevelError] = u8"错误";
}

Log::~Log(void)
{
}

Log& Log::getInstance()
{
    // 返回QLog的单例对象
    static Log s_log;
    return s_log;
}

void Log::setDir(const QString& dirPath)
{
    m_sDir = dirPath;
    QDir dir;
    if (dir.exists(m_sDir) == false)
    {
        dir.mkpath(m_sDir);
    }
}

void Log::log(eLogLevel level, const std::wstring& msg)
{
    QDateTime curDateTime = QDateTime::currentDateTime();
    QString fileName = m_sDir + u8"/" + curDateTime.toString(u8"yyyyMMdd") + u8".txt";
    QFile file(fileName);

    std::unique_lock<std::mutex>(m_mutexSerialize);
    if (file.open(QIODevice::Text | QIODevice::WriteOnly | QIODevice::Append) == true)
    {
        QTextStream out(&file);
        // 写入标签
        out << u8"[" << m_softName << "-" << m_softVersion << "]";
        // 写入时间
        out << u8"[" << curDateTime.toString(u8"yyyy-MM-dd hh:mm:ss:zzz") << u8"]";
        // 写入类型
        out << u8"[" << m_sLogLevel[level] << u8"]";
        // 写入内容
        out << QString::fromStdWString(msg) << endl;
        file.close();
    }
}

void jsdk::Log::setSoftName(const QString& softName)
{
    m_softName = softName;
}

const QString& jsdk::Log::getSoftName() const
{
    return m_softName;
}

void jsdk::Log::setSoftVersion(const QString& softVersion)
{
    m_softVersion = softVersion;
}

const QString& jsdk::Log::getSoftVersion() const
{
    return m_softVersion;
}
